package com.hyyt.shopjsp.basic.controller;

import com.hyyt.shopjsp.basic.pojo.BasicUsers;
import com.hyyt.shopjsp.basic.service.IBasicActorService;
import com.hyyt.shopjsp.basic.service.IBasicUsersService;
import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.StringStaticKey;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.redis.service.IRedisBasicService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Copyright (c) 2016 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授LQS权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 * @author  on 2016/10/19 0019上午 11:09.
 */
@Controller
@RequestMapping("/backLogin")
public class LoginController extends BaseController {
    private Logger logger = Logger.getLogger(LoginController.class);
    private final String basePath = "/back/login/";

    @Resource
    private IBasicUsersService basicUsersService;
    @Resource
    private IRedisBasicService redisBasicService;
    @Resource
    private IBasicActorService basicActorService;

    /**
     * 登录主页
     *
     * @return
     */
    @RequestMapping("index")
    public String index(HttpServletRequest request) {
        return basePath + "backLogin";
    }

    /**
     * shiro 退出登录
     *
     * @return
     */
    @RequestMapping("goToExit")
    public String goToExit(HttpServletResponse response, HttpServletRequest request) {
        //清空session数据
        session.invalidate();
        return forward("/backLogin/index.htm");
    }

    /**
     * 用户登录验证
     *
     * @param userName    管理员用户名
     * @param password    密码
     * @param response
     * @param request
     * @return
     */
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public ResultMsg login(String userName, String password, HttpServletResponse response, HttpServletRequest request) {
        ResultMsg rm = new ResultMsg(false);
        String message = "";
        if (!Utils.stringIsNotEmpty(userName) || !Utils.stringIsNotEmpty(password)) {
            message="登录信息有误，请重新输入！";
        }else{
            /**
             * shiro 登录验证
             */
            ResultMsg rMsg = loginSafeValidate(userName, password);
            if (rMsg.isSuccess()) {
                BasicUsers basicUsers = basicUsersService.getBasicUsersByUserName(userName);
                if (basicUsers.getLockState().compareTo(1) == 0) {//0：表示未锁，1：表示已锁
                    message = "当前账号已冻结，不能登录！";
                }else{
                    message = "登录成功";
                    session.setAttribute(StringStaticKey.SESSION_USERS, basicUsers);
                    rm.setSuccess(true);
                }
            }else{
                message = rMsg.getMsg();
            }
        }
        rm.setMsg(message);
        return rm;
    }


    /**
     * shiro登录安全认证
     *
     * @param userName 管理员用户名
     * @param password 密码
     * @return
     */
    private ResultMsg loginSafeValidate(String userName, String password) {
        ResultMsg resultMsg = new ResultMsg(false);
        try {
            UsernamePasswordToken token = new UsernamePasswordToken(userName.trim(), password);
            Subject currentUser = SecurityUtils.getSubject();
            if (!currentUser.isAuthenticated()) {
                //使用shiro来验证
                token.setRememberMe(false);
            }
            currentUser.login(token);//验证用户登录
            resultMsg.setSuccess(true);
            resultMsg.setMsg("登录验证成功！");

        } catch (Exception e) {
            resultMsg.setSuccess(false);
            resultMsg.setMsg("用户名或密码错误！");
            logger.error("登录异常：" + e);
        }
        return resultMsg;
    }



}
